package com.guxingke.nioserver.core;

import com.guxingke.nioserver.exception.ServerException;

import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;
import java.util.List;

public final class Writer extends Thread {
    private static List<SelectionKey> pool = new LinkedList<SelectionKey>();
    private static Notifier notifier = Notifier.getNotifier();

    public Writer() {
    }

    public void run() {
        while (true) {
            try {
                SelectionKey key;
                synchronized (pool) {
                    while (pool.isEmpty()) {
                        pool.wait();
                    }
                    key = (SelectionKey) pool.remove(0);
                }

                write(key);
            } catch (Exception e) {
                continue;
            }
        }
    }

    private void write(SelectionKey key) {
        SocketChannel sc = (SocketChannel) key.channel();
        HttpResponse response = new HttpResponse();
        response.setSocketChannel(sc);
        try {
            notifier.fireOnWrite((HttpRequest) key.attachment(), response);
            sc.finishConnect();
            sc.socket().close();
            sc.close();
            notifier.fireOnClosed((HttpRequest) key.attachment());
        } catch (Exception e) {
            notifier.fireOnError(new ServerException(600));
        }
    }

    public static void processRequest(SelectionKey key) {
        synchronized (pool) {
            pool.add(pool.size(), key);
            pool.notifyAll();
        }
    }
}
